package com.king.photo.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.king.photo.adapter.AlbumGridViewAdapter;
import com.king.photo.util.AlbumHelper;
import com.king.photo.util.Bimp;
import com.king.photo.util.HttpRequest;
import com.king.photo.util.ImageBucket;
import com.king.photo.util.ImageItem;
import com.king.photo.util.PublicWay;
import com.king.photo.util.Res;
import com.shouxun.microclassroom.R;
import com.shouxun.microclassroom.SetActivity;

/**
 * 这个是进入相册显示所有图片的界面
 * 
 * @author king
 * @QQ:595163260
 * @version 2014年10月18日 下午11:47:15
 */
public class Album2Activity extends Activity {
	// 显示手机里的所有图片的列表控件
	private GridView gridView;
	// 当手机里没有图片时，提示用户没有图片的控件
	private TextView tv;
	// gridView的adapter
	private AlbumGridViewAdapter gridImageAdapter;
	// 完成按钮
	private Button okButton;
	// 返回按钮
	private Button back;
	// 取消按钮
	private Button cancel;
	private Intent intent;
	// 预览按钮
	private Button preview;
	private Context mContext;
	private ArrayList<ImageItem> dataList;
	private AlbumHelper helper;
	public static List<ImageBucket> contentList;
	public static Bitmap bitmap;
	String path;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.plugin_camera_album);
		PublicWay.activityList.add(this);
		mContext = this;
		bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.plugin_camera_no_pictures);
		init();
		initListener();
		// 这个函数主要用来控制预览和完成按钮的状态
		isShowOkBt();
	}

	

	// 预览按钮的监听
	private class PreviewListener implements OnClickListener {
		public void onClick(View v) {
			if (Bimp.tempSelectBitmap.size() > 0) {
				intent.putExtra("position", "1");
				intent.setClass(Album2Activity.this, GalleryActivity.class);
				startActivity(intent);
			}
		}

	}

	// 完成按钮的监听
	private class AlbumSendListener implements OnClickListener {
		public void onClick(View v) {
			new Thread() {
				public void run() {
					StringBuffer sb = new StringBuffer();
					for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
						ImageItem item = Bimp.tempSelectBitmap.get(i);
						String urlPath = "http://www.17smile.cn/app/uploadimagefile";
						HttpRequest request = HttpRequest.post(urlPath);
						request.part("fileType", "vote");
						request.part("flag", "image");
						request.part("imageName",item.getThumbnailPath().split("Thumb")[1]);
						request.part("uploadimage",
								new File(item.getImagePath()));
						String path=request.body();
						
							sb.append(path+","+item.getImagePath()+",")	; 
						
					}
					final String s = sb.substring(0, sb.length() - 1);
					System.out.println(s.toString());
					Message msg=new Message();
					msg.obj=s;
					handler.sendMessage(msg);
				}
			}.start();
			
		}

	}

	// 返回按钮监听
	private class BackListener implements OnClickListener {
		public void onClick(View v) {
			finish();
		}
	}

	// 取消按钮的监听
	private class CancelListener implements OnClickListener {
		public void onClick(View v) {
			Bimp.tempSelectBitmap.clear();
			intent.setClass(mContext, SetActivity.class);
			startActivity(intent);
		}
	}

	// 初始化，给一些对象赋值
	private void init() {
		helper = AlbumHelper.getHelper();
		helper.init(getApplicationContext());

		contentList = helper.getImagesBucketList(false);
		dataList = new ArrayList<ImageItem>();
		for (int i = 0; i < contentList.size(); i++) {
			dataList.addAll(contentList.get(i).imageList);
		}

		back = (Button) findViewById(R.id.back);
		cancel = (Button) findViewById(R.id.cancel);
		cancel.setOnClickListener(new CancelListener());
		back.setOnClickListener(new BackListener());
		preview = (Button) findViewById(R.id.preview);
		preview.setOnClickListener(new PreviewListener());
		intent = getIntent();
		gridView = (GridView) findViewById(R.id.myGrid);
		gridImageAdapter = new AlbumGridViewAdapter(this, dataList,
				Bimp.tempSelectBitmap);
		gridView.setAdapter(gridImageAdapter);
		tv = (TextView) findViewById(R.id.myText);
		gridView.setEmptyView(tv);
		okButton = (Button) findViewById(R.id.ok_button);
		okButton.setText("已选" + "(" + Bimp.tempSelectBitmap.size() + "/"
				+ PublicWay.num + ")");
	}

	private void initListener() {

		gridImageAdapter
				.setOnItemClickListener(new AlbumGridViewAdapter.OnItemClickListener() {

					@Override
					public void onItemClick(final ToggleButton toggleButton,
							int position, boolean isChecked, Button chooseBt) {
						if (Bimp.tempSelectBitmap.size() >= PublicWay.num) {
							toggleButton.setChecked(false);
							chooseBt.setVisibility(View.GONE);
							if (!removeOneData(dataList.get(position))) {
								Toast.makeText(Album2Activity.this,
										Res.getString("only_choose_num"), 200)
										.show();
							}
							return;
						}
						if (isChecked) {
							chooseBt.setVisibility(View.VISIBLE);
							ImageItem item = dataList.get(position);
							TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
							String szImei = TelephonyMgr.getDeviceId(); 
							
							String fileName = String.valueOf("Thumb"
									+szImei+ System.currentTimeMillis());
							String fileName1 = String.valueOf(szImei+System
									.currentTimeMillis());
							Bitmap b = item.getBitmap();
							isExist("/sdcard/Photo_LJ/");
							File f = new File("/sdcard/Photo_LJ/", fileName
									+ ".png");
							File f1 = new File("/sdcard/Photo_LJ/", fileName1
									+ ".png");
							FileOutputStream out, out1;
							try {
								out = new FileOutputStream(f);
								out1 = new FileOutputStream(f1);
								b.compress(Bitmap.CompressFormat.PNG, 50, out);
								b.compress(Bitmap.CompressFormat.PNG, 100, out1);
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							item.setImagePath(f1.getPath());
							item.setThumbnailPath(f.getPath());
							Bimp.tempSelectBitmap.add(item);
							okButton.setText("已选" + "("
									+ Bimp.tempSelectBitmap.size() + "/"
									+ PublicWay.num + ")");
						} else {
							ImageItem item = dataList.get(position);
							String fileName = String.valueOf("Thumb"
									+ System.currentTimeMillis());
							String fileName1 = String.valueOf(System
									.currentTimeMillis());
							Bitmap b = item.getBitmap();
							File f = new File("/sdcard/Photo_LJ/", fileName
									+ ".png");
							File f1 = new File("/sdcard/Photo_LJ/", fileName1
									+ ".png");
							FileOutputStream out, out1;
							try {
								out = new FileOutputStream(f);
								out1 = new FileOutputStream(f1);
								b.compress(Bitmap.CompressFormat.PNG, 50, out);
								b.compress(Bitmap.CompressFormat.PNG, 100, out1);
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							item.setImagePath(f1.getPath());
							item.setThumbnailPath(f.getPath());
							Bimp.tempSelectBitmap.remove(item);
							chooseBt.setVisibility(View.GONE);
							okButton.setText("已选" + "("
									+ Bimp.tempSelectBitmap.size() + "/"
									+ PublicWay.num + ")");
						}
						isShowOkBt();
					}
				});

		okButton.setOnClickListener(new AlbumSendListener());

	}

	private boolean removeOneData(ImageItem imageItem) {
		if (Bimp.tempSelectBitmap.contains(imageItem)) {
			Bimp.tempSelectBitmap.remove(imageItem);
			okButton.setText("已选" + "(" + Bimp.tempSelectBitmap.size() + "/"
					+ PublicWay.num + ")");
			return true;
		}
		return false;
	}

	public void isShowOkBt() {
		if (Bimp.tempSelectBitmap.size() > 0) {
			okButton.setText("已选" + "(" + Bimp.tempSelectBitmap.size() + "/"
					+ PublicWay.num + ")");
			preview.setPressed(true);
			okButton.setPressed(true);
			preview.setClickable(true);
			okButton.setClickable(true);
			okButton.setTextColor(Color.WHITE);
			preview.setTextColor(Color.WHITE);
		} else {
			okButton.setText("已选" + "(" + Bimp.tempSelectBitmap.size() + "/"
					+ PublicWay.num + ")");
			preview.setPressed(false);
			preview.setClickable(false);
			okButton.setPressed(false);
			okButton.setClickable(false);
			okButton.setTextColor(Color.parseColor("#E1E0DE"));
			preview.setTextColor(Color.parseColor("#E1E0DE"));
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return false;

	}

	@Override
	protected void onRestart() {
		isShowOkBt();
		super.onRestart();
	}

	public static void isExist(String path) {
		File file = new File(path);
		// 判断文件夹是否存在,如果不存在则创建文件夹
		if (!file.exists()) {
			file.mkdir();
		}
	}
	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			path=msg.obj.toString();
			Toast.makeText(getApplicationContext(), path,3000).show();
			overridePendingTransition(R.anim.activity_translate_in,
					R.anim.activity_translate_out);
			
			finish();
		}
	};
}
